package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.entity.*;
import com.sjb.sixteen_journey_backend.entity.dto.ComeFriendDto;
import com.sjb.sixteen_journey_backend.entity.vo.UserBaseMsgVo;
import com.sjb.sixteen_journey_backend.mapper.ComeFriendMapper;
import com.sjb.sixteen_journey_backend.mapper.CommonnessMapper;
import com.sjb.sixteen_journey_backend.mapper.FollowerMapper;
import com.sjb.sixteen_journey_backend.service.IComeFriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.service.ICommentService;
import com.sjb.sixteen_journey_backend.service.IUserService;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 约伴表 服务实现类
 * </p>
 *
 * @author jcz
 * @since 2024-08-18
 */
@Service
public class ComeFriendServiceImpl extends ServiceImpl<ComeFriendMapper, ComeFriend> implements IComeFriendService {

    @Autowired
    private ICommentService commentService;

    @Autowired
    private FollowerMapper followerMapper;

    @Autowired
    private CommonnessMapper commonnessMapper;

    @Autowired
    private IUserService userService;
    @Override
    public R<ComeFriend> addMyFriendTable(ComeFriend comeFriend) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer id = (Integer) map.get("id");
            comeFriend.setUserId(id);
            if(!this.save(comeFriend)){
                return R.error("添加约伴失败");
            }

            comeFriend = this.getById(comeFriend.getComeFriendId());
            //评价数量 当前用户是否关注发帖人 发帖人的基本信息
            User user = userService.getUserById(comeFriend.getUserId());
            comeFriend = this.setCountAndFollow(comeFriend);
            UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
            BeanUtils.copyProperties(user, userBaseMsgVo);
            comeFriend.setUser(userBaseMsgVo);

            return R.success(comeFriend, "添加约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<ComeFriend> changeMyFriendTable(ComeFriend comeFriend) {
        try {
            if(this.getById(comeFriend.getComeFriendId())==null) return R.error("没有该约伴");
            if(!this.updateById(comeFriend)) return R.error("修改约伴失败");

            comeFriend = this.getById(comeFriend.getComeFriendId());
            //评价数量 当前用户是否关注发帖人 发帖人的基本信息
            User user = userService.getUserById(comeFriend.getUserId());
            comeFriend = this.setCountAndFollow(comeFriend);
            UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
            BeanUtils.copyProperties(user, userBaseMsgVo);
            comeFriend.setUser(userBaseMsgVo);

            return R.success(comeFriend, "修改约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R deleteMyFriendTable(Integer id) {
        try {
            if(this.getById(id)==null) return R.error("没有该约伴");
            if(!this.removeById(id)) return R.error("删除约伴失败");
            return R.success(null, "删除约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<ComeFriend>> getAllFriendTable() {
        try {
            List<ComeFriend> friendList =new ArrayList<>();
            List<ComeFriend> list = this.list();
            if(list.size()<0) return R.success(null, "没有约伴");

            //评价数量 当前用户是否关注发帖人 发帖人的基本信息
            for(ComeFriend myTime:list){
                User user = userService.getUserById(myTime.getUserId());
                ComeFriend comeFriend = this.setCountAndFollow(myTime);
                UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
                BeanUtils.copyProperties(user, userBaseMsgVo);
                comeFriend.setUser(userBaseMsgVo);
                friendList.add(comeFriend);
            }

            return R.success(friendList, "获取约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<ComeFriend>> getMyFriendTable() {
        try {
            List<ComeFriend> friendList =new ArrayList<>();
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer id = (Integer) map.get("id");
            QueryWrapper<ComeFriend> wrapper = Wrappers.query();
            wrapper.eq("user_id",id);
            List<ComeFriend> list = this.list(wrapper);

            //评价数量 当前用户是否关注发帖人 发帖人的基本信息
            for(ComeFriend myTime:list){
                User user = userService.getUserById(myTime.getUserId());
                ComeFriend comeFriend = this.setCountAndFollow(myTime);
                UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
                BeanUtils.copyProperties(user, userBaseMsgVo);
                comeFriend.setUser(userBaseMsgVo);
                friendList.add(comeFriend);
            }

            return R.success(friendList, "获取约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<ComeFriend> getFriendTableById(Integer id) {
        try {
            ComeFriend comeFriend = this.getById(id);
            if(comeFriend==null) return R.error("没有该约伴");

            //评价数量 当前用户是否关注发帖人 发帖人的基本信息
            User user = userService.getUserById(comeFriend.getUserId());
            comeFriend = this.setCountAndFollow(comeFriend);
            UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
            BeanUtils.copyProperties(user, userBaseMsgVo);
            comeFriend.setUser(userBaseMsgVo);

            return R.success(comeFriend, "获取约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<ComeFriend>> getFriendTableByCondition(ComeFriendDto comeFriendDto) {
        try {
            List<ComeFriend> friendList =new ArrayList<>();

            QueryWrapper<ComeFriend> queryWrapper = new QueryWrapper<>();
            if(comeFriendDto.getStartTime() != null) queryWrapper.le("start_time", comeFriendDto.getEndTime());
            if(comeFriendDto.getEndTime()!=null)   queryWrapper.ge("end_time", comeFriendDto.getStartTime());
            if(comeFriendDto.getDestination()!=null)   queryWrapper.eq("destination", comeFriendDto.getDestination());
            if(comeFriendDto.getPlaceOfDeparture()!=null) queryWrapper.eq("place_of_departure", comeFriendDto.getPlaceOfDeparture());
            List<ComeFriend> list = this.list(queryWrapper);

            //评价数量 当前用户是否关注发帖人 发帖人的基本信息
            for(ComeFriend myTime:list){
                User user = userService.getUserById(myTime.getUserId());
                ComeFriend comeFriend = this.setCountAndFollow(myTime);
                UserBaseMsgVo userBaseMsgVo = new UserBaseMsgVo();
                BeanUtils.copyProperties(user, userBaseMsgVo);
                comeFriend.setUser(userBaseMsgVo);
                friendList.add(comeFriend);
            }
            return R.success(friendList, "获取约伴成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private ComeFriend setCountAndFollow(ComeFriend myTime) {
        Map<String, Object> map = ThreadLocalUtil.get();
        //我的此刻的评论数量
        QueryWrapper<Comment> query = Wrappers.query();
        query.eq("module_status",myTime.getStatus());
        query.eq("module_id", myTime.getComeFriendId());
        long count = commentService.count(query);
        myTime.setCommentCount(count);

        Follower follower = new Follower();
        Commonness commonness = new Commonness();
        if(map!=null){
            Integer userId = (Integer) map.get("id");
            //当前用户对该用户是否关注
            QueryWrapper<Follower> followerQueryWrapper = Wrappers.query();
            followerQueryWrapper.eq("user_id",userId);
            followerQueryWrapper.eq("fans_id", myTime.getUserId());
            follower = followerMapper.selectOne(followerQueryWrapper);
            //当前用户对该地图的关注和收藏情况
            QueryWrapper<Commonness> wrapperCommonness = Wrappers.query();
            wrapperCommonness.eq("status", myTime.getStatus());
            wrapperCommonness.eq("module_id", myTime.getComeFriendId());
            wrapperCommonness.eq("user_id", userId);
            commonness = commonnessMapper.selectOne(wrapperCommonness);
        }
        myTime.setIs_followedByUser(follower==null ? false :follower.getStatus());
        if(commonness!=null){
            myTime.setCommonness(commonness);
        }

        return myTime;
    }
}
